﻿using System.Collections.Generic;
using System.Text;

namespace DanMuHelper.Cache
{
    /// <summary>
    /// StringBuilder缓存
    /// </summary>
    public static class CachedStringBuilder
    {
        private static List<StringBuilder> _sbPool;
        public static StringBuilder Create()
        {
            StringBuilder sb;
            if (null == _sbPool || _sbPool.Count == 0)
            {
                sb = new StringBuilder();
            }
            else
            {
                var pos = _sbPool.Count - 1;
                sb = _sbPool[pos];
                _sbPool.RemoveAt(pos);
            }
            return sb;
        }

        public static void Return(ref StringBuilder sb)
        {
            if (null == _sbPool)
            {
                _sbPool = new List<StringBuilder>();
                sb.Clear();
                _sbPool.Add(sb);
            }
            else
            {
                if (_sbPool.Count < 8)
                {
                    sb.Clear();
                    _sbPool.Add(sb);
                }
            }
            sb = null;
        }
    }
}
